package com.example.server.plugins.routing

import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File


private val logger: Logger = LoggerFactory.getLogger("FileUpload")

/**
 * 文件上传
 * https://ktor.io/docs/requests.html#form_data
 */
fun Route.configFileUploadRouting() {
    post("/upload") {
        val multipartData = call.receiveMultipart()
        try {
            multipartData.forEachPart { part ->
                when (part) {
                    is PartData.FormItem -> {
                        logger.info("${part.name} = ${part.value}")
                    }
                    is PartData.FileItem -> {
                        val fileName = part.originalFileName as String
                        val fileBytes = part.streamProvider().readBytes()
                        File("uploads/$fileName").writeBytes(fileBytes)
                    }
                    else -> {
                        logger.info("${part.name} = ${part.contentType}")
                    }
                }
            }
            call.respond("upload ok")
        } catch (e: java.lang.Exception) {
            call.respond(e)
        }
    }

    /**
     * https://ktor.io/docs/responses.html#file
     */
    get("/download/{filename}") {
        val filename = call.parameters["filename"]
        if (filename.isNullOrBlank()) {
            return@get
        }
        val file = File(filename) // "uploads/大气压力.svg"
        logger.info(file.absolutePath)
        if (file.exists()) {
            call.response.header(
                HttpHeaders.ContentDisposition,
                ContentDisposition.Attachment.withParameter(ContentDisposition.Parameters.FileName, file.name)
                    .toString()
            )
            call.respondFile(file)
        }
    }
}